<?php

namespace frontend\modules\shop\controllers;

use common\models\shop\ShopCart;
use frontend\controllers\BaseMobileController;
use yii\web\NotFoundHttpException;


/**
 * Class OrderController
 * @package frontend\modules\shop\controllers
 * 购物车相关控制器
 */
class CartController extends BaseMobileController
{



    /**
     * 购物车页面
     */
    public function actionIndex()
    {

        return $this->render('@template/mobile/cart.html',[
        ]);

    }



    /**
     * 插入购物车跳转到订单确认页面，（立刻结算）
     */
    public function actionInsert()
    {
        $postdata = \Yii::$app->request->post();
        foreach ($postdata as $key => $row){
            $data = [
                'goodsid' => $row['goodsid'],
                'openid' => $this->user['openid'],
                'total' => $row['total'],
                'productprice' => $row['price'],
            ];
            $res = \Yii::$app->db->createCommand()
                ->insert(ShopCart::tableName(),$data)
                ->execute();
        }

        return $res?$this->jsonMsg():$this->jsonMsg('更新购物车失败',1,['url' => Url::to(['/shop/site/confirm'])]);
    }



    /**
     * @param $cartid
     * @return array
     * 删除购物车
     */
    public function actionDelete($cartid)
    {
        $cart = self::findModel($cartid)->delete();
        return $this->jsonMsg();
    }



    protected function findModel($id)
    {
        if (($model = ShopCart::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }



}